
package us.hornerscorners.lollipop.web;

/*
* #%L
 * * LollipopRouter
 * *
 * %%
 * Copyright (C) 2013 - 2014 Jim Horner
 * *
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */

import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.HapiContext;
import javax.annotation.Resource;

import javax.enterprise.concurrent.ManagedThreadFactory;

import javax.inject.Inject;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import javax.servlet.annotation.WebListener;

import ca.uhn.hl7v2.app.HL7Service;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import us.hornerscorners.lollipop.config.LollipopConfig;

import us.hornerscorners.lollipop.hapi.IHL7ServiceDecorator;
import us.hornerscorners.lollipop.hapi.RoutingApplication;


/**
 * Class description
 *
 *
 * @version        v1.0, 2014-09-06
 * @author         Jim Horner
 */
@WebListener
public class RoutingStartupListener implements ServletContextListener {

    /** Field description */
    @Inject
    private LollipopConfig config;

    /** Field description */
    @Inject
    private IHL7ServiceDecorator decorator;

    /** Field description */
    private HL7Service hl7Service;

    /** Field description */
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /** Field description */
    @Resource
    private ManagedThreadFactory threadFactory;

    /**
     * Method description
     *
     *
     * @param sce
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {

        if (this.hl7Service.isRunning()) {

            logger.info("Stopping listener on port {}.", this.config.getPort());
            this.hl7Service.stopAndWait();

        } else {

            logger.info("Service on port {} not running.", this.config.getPort());
        }
    }

    /**
     * Method description
     *
     *
     * @param sce
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {

        ExecutorService hapiThreads =
            new ThreadPoolExecutor(
                config.getThreadPoolSize(), config.getThreadPoolMax(),
                config.getThreadKeepAlive(), TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(config.getThreadPoolMax()),
                this.threadFactory);

        HapiContext hapiContext = new DefaultHapiContext(hapiThreads);

        int port = this.config.getPort();

        this.hl7Service = hapiContext.newServer(port, false);

        this.decorator.decorate(this.hl7Service);

        this.hl7Service.registerApplication(new RoutingApplication(hapiContext,
                config.getRoutings()));

        logger.info("Starting listener on port {} ...", port);

        try {

            this.hl7Service.startAndWait();

        } catch (Exception e) {

            logger.error("Error in startup", e);

            throw new IllegalStateException(e);
        }

    }
}
